package com.zhipu.balance.ui.vm.home.calculate.rice

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zhipu.balance.common.Constants
import com.zhipu.balance.listener.ChooseClickCallback
import com.zhipu.balance.listener.SerialPortListener
import com.zhipu.balance.mobile.dao.NumberDao
import com.zhipu.balance.mobile.dao.RecordRiceDao
import com.zhipu.balance.mobile.event.RecordRice
import com.zhipu.balance.pop.ConfirmPopup
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.calculate.rice.*
import com.zhipu.balance.ui.home.calculate.rice.adapter.RiceAdapter
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.OpenSerialPort
import com.zhipu.balance.utils.data.DisposeUtils
import com.zhipu.balance.utils.print.rice.RicePrintUtils
import com.zhipu.balance.utils.upload.rice.RiceUploadUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 功能计算-稻谷
 */
class RiceViewModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService), SerialPortListener,ChooseClickCallback {
    /**
     * 称重重量
     */
    var weighing = ObservableField("0.00")

    /**
     * 去皮
     */
    var peel = ObservableField(false)

    /**
     * 位置
     */
    var mPosition = MutableLiveData(0)

    /**
     * 编号
     */
    var mNumber = ObservableField("")

    /**
     * 日期
     */
    var mInspectionDate = ObservableField("")

    /**
     * 记录稻谷
     */
    var mRecordRice = RecordRice()



    /**
     * 适配器
     */
    var mRiceAdapter : RiceAdapter? = null



    /**
     *  Fragment集合
     */
    var mFragments = MutableLiveData<List<Fragment>>()

    /**
     * 稻谷杂质
     */
    var mRiceImpurityFragment = RiceImpurityFragment(mRecordRice)
    /**
     * 稻谷谷外糙米
     */
    var mRiceBrownFragment = RiceBrownFragment(mRecordRice)
    /**
     * 稻谷出糙率
     */
    var mRiceRougheningFragment = RiceRougheningFragment(mRecordRice)

    /**
     * 稻谷整精米
     */
    var mRiceFinishingFragmeent = RiceFinishingFragment(mRecordRice)
    /**
     * 稻谷黄粒米
     */
    var mRiceYellowGrainFragment = RiceYellowGrainFragment(mRecordRice)

    /**
     * 互混
     */
    var mRiceIntermixingFragment = RiceIntermixingFragment(mRecordRice)
    /**
     * 出米率
     */
    var mRiceYieldFragment = RiceYieldFragment(mRecordRice)


    init {
        OpenSerialPort.onSerialPortListener(this)
        /**
         * 每隔milliseconds毫秒后执行next操作
         */
        Observable.interval(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(object :
            Observer<Long> {

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: Long) {
                /**
                 * 重量輸出命令
                 */
                OpenSerialPort.output()
            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }

        })
        /**
         * Fragment适配器
         */
        var mFragmentList = mutableListOf<Fragment>()
        //稻谷杂质
        mFragmentList.add(mRiceImpurityFragment)
        //稻谷谷外糙米
        mFragmentList.add(mRiceBrownFragment)
        //稻谷出糙率
        mFragmentList.add(mRiceRougheningFragment)
        //稻谷整精米
        mFragmentList.add(mRiceFinishingFragmeent)
        //稻谷黄粒米
        mFragmentList.add(mRiceYellowGrainFragment)
        //互混
        mFragmentList.add(mRiceIntermixingFragment)
        //出米率
        mFragmentList.add(mRiceYieldFragment)
        /**
         * Fragment集合
         */
        mFragments.postValue(mFragmentList)
        /**
         * 适配器
         */
        mRiceAdapter = RiceAdapter(this);

    }

    /**
     * 重量回调
     */
    override fun itemClicked(event: ByteArray?) {
        /**
         * 数值
         */
        val numericalValue = ConvertUtils.bytes2HexString(event)
        if (event!!.size >= 10) {
            if (numericalValue == Constants.FARMAR_500) {
                weighing.set("砝码500")
            } else if (numericalValue == Constants.FARMAR_1000) {
                weighing.set("砝码1000")
            } else if (numericalValue == Constants.FARMAR_2000) {
                weighing.set("砝码2000")
            }else if (numericalValue == Constants.FARMAR_3000) {
                weighing.set("砝码3000")
            } else if (numericalValue == Constants.CALIBRATION_500) {
                weighing.set("完成定标")
            } else if (numericalValue == Constants.OVERLOAD) {
                weighing.set("超重")
            } else if (numericalValue == Constants.SEND_GO_START) {
                InitializeUtils.getDefaultMaker()?.show("去皮成功")
                peel.set(false)
            }  else if (numericalValue == Constants.SHIELD) {
                weighing.set("校准中")
            } else {
                if(peel.get() == true){
                    /**
                     * 置零命令
                     */
                    OpenSerialPort.ZeroOrder()
                }
                var weight = DisposeUtils.balanceCorrection(event)
                //稻谷杂质
                mRiceImpurityFragment.setWeighing(weight)
                //稻谷谷外糙米
                mRiceBrownFragment.setWeighing(weight)
                //稻谷出糙率
                mRiceRougheningFragment.setWeighing(weight)
                //稻谷整精米
                mRiceFinishingFragmeent.setWeighing(weight)
                //稻谷黄粒米
                mRiceYellowGrainFragment.setWeighing(weight)
                //互混
                mRiceIntermixingFragment.setWeighing(weight)
                //出米率
                mRiceYieldFragment.setWeighing(weight)

                weighing.set(weight)
            }
        }
    }


    /**
     * Fragment回调
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun onChooseClickCallback(mInt: Int) {
        mRiceAdapter?.notifyDataSetChanged()
        mPosition.postValue(mInt)
        when(mInt){
            0 ->{
                //稻谷杂质
                mRiceImpurityFragment.updateRecordRice(mRecordRice)
            }
            1 ->{
                //稻谷谷外糙米
                mRiceBrownFragment.updateRecordRice(mRecordRice)
                mRiceBrownFragment.LargeImpurityRate()
            }
            2 ->{
                //稻谷出糙率
                mRiceRougheningFragment.updateRecordRice(mRecordRice)
            }
            3 ->{
                //稻谷整精米
                mRiceFinishingFragmeent.updateRecordRice(mRecordRice)
                mRiceFinishingFragmeent.refreshData()
            }
            4 ->{
                //稻谷黄粒米
                mRiceYellowGrainFragment.updateRecordRice(mRecordRice)
            }
            5 ->{
                //互混
                mRiceIntermixingFragment.updateRecordRice(mRecordRice)
            }
            6 ->{
                //出米率
                mRiceYieldFragment.updateRecordRice(mRecordRice)
            }
        }

    }

    /**
     * 更新数据
     */
    fun UpdatePage(productCategoryText : String){
        var mRecordRice = RecordRiceDao.getInstance().QueryByNumber(productCategoryText)
        if(mRecordRice.recordRiceId > 0){
            this.mRecordRice = mRecordRice
            //日期
            mInspectionDate.set(TimeUtils.millis2String(mRecordRice.inspectionDate))
            //稻谷杂质
            mRiceImpurityFragment.updateRecordRice(mRecordRice)
            //稻谷谷外糙米
            mRiceBrownFragment.updateRecordRice(mRecordRice)
            //稻谷出糙率
            mRiceRougheningFragment.updateRecordRice(mRecordRice)
            //稻谷整精米
            mRiceFinishingFragmeent.updateRecordRice(mRecordRice)
            //稻谷黄粒米
            mRiceYellowGrainFragment.updateRecordRice(mRecordRice)
            //互混
            mRiceIntermixingFragment.updateRecordRice(mRecordRice)
            //出米率
            mRiceYieldFragment.updateRecordRice(mRecordRice)
        }else{
            //唯一识别码
            mRecordRice.uniqueId = productCategoryText
            //日期
            mInspectionDate.set(TimeUtils.millis2String(TimeUtils.getNowMills()))
        }
        //编号
        mNumber.set(productCategoryText)

    }

    /**
     * 释放更新页面
     */
    fun releaseRecordRice(){
        mRecordRice = RecordRice()
        //稻谷杂质
        mRiceImpurityFragment.setRecordRice(mRecordRice)
        mRiceImpurityFragment.releaseRecordRice()
        //稻谷谷外糙米
        mRiceBrownFragment.setRecordRice(mRecordRice)
        mRiceBrownFragment.releaseRecordRice()
        //稻谷出糙率
        mRiceRougheningFragment.setRecordRice(mRecordRice)
        mRiceRougheningFragment.releaseRecordRice()
        //稻谷整精米
        mRiceFinishingFragmeent.setRecordRice(mRecordRice)
        mRiceFinishingFragmeent.releaseRecordRice()
        //稻谷黄粒米
        mRiceYellowGrainFragment.setRecordRice(mRecordRice)
        mRiceYellowGrainFragment.releaseRecordRice()
        //互混
        mRiceIntermixingFragment.setRecordRice(mRecordRice)
        mRiceIntermixingFragment.releaseRecordRice()
        //出米率
        mRiceYieldFragment.setRecordRice(mRecordRice)
        mRiceYieldFragment.releaseRecordRice()
        //编号
        mNumber.set("")
        //日期
        mInspectionDate.set("")
    }

    /**
     * 更新页面
     */
    fun updatePage(mRecordRice : RecordRice){
        this.mRecordRice = mRecordRice
        //编号
        mNumber.set(mRecordRice.uniqueId)
        //日期
        mInspectionDate.set(TimeUtils.millis2String(mRecordRice.inspectionDate))
        //稻谷杂质
        mRiceImpurityFragment.updateRecordRice(mRecordRice)
        //稻谷谷外糙米
        mRiceBrownFragment.updateRecordRice(mRecordRice)
        //稻谷出糙率
        mRiceRougheningFragment.updateRecordRice(mRecordRice)
        //稻谷整精米
        mRiceFinishingFragmeent.updateRecordRice(mRecordRice)
        //稻谷黄粒米
        mRiceYellowGrainFragment.updateRecordRice(mRecordRice)
        //互混
        mRiceIntermixingFragment.updateRecordRice(mRecordRice)
        //出米率
        mRiceYieldFragment.updateRecordRice(mRecordRice)
    }


    /**
     * 保存
     */
    fun save(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    //唯一识别码
                    mRecordRice.uniqueId = mNumber.get()
                    //判断
                    if(mRecordRice.recordRiceId > 0){
                        //设备码
                        mRecordRice.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        mRecordRice.update()
                    }else{
                        //设备码
                        mRecordRice.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        if(mRecordRice.save()){
                            /**
                             * 上传
                             */
                            val NetworkSettings = SPUtils.getInstance().getString("NetworkSettings")
                            if(TextUtils.isEmpty(NetworkSettings)){
                                //外网上传稻谷天平数据
                                RiceUploadUtils.uploadRiceBalanceInfo(mRecordRice,null)
                            }else{
                                //内网上传稻谷天平数据
                                RiceUploadUtils.IntranetRiceBalanceInfo(mRecordRice,null)
                            }
                        }
                    }
                    /**
                     * 释放更新页面
                     */
                    releaseRecordRice()
                    /**
                     * 数量加一
                     */
                    SPUtils.getInstance().put("number", SPUtils.getInstance().getInt("number") + 1)
                }
            }
        },"确认要进行上传并保存吗 \n 确认之后会进行新一轮的计算")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }



    /**
     * 打印
     */
    fun print(){
        if(InitializeUtils.isLinkPrinter()){
            var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
                override fun onChooseClickCallback(mInt: Int) {
                    if(mInt == 0){
                        RicePrintUtils.RicPrinting(mRecordRice)
                    }
                }
            },"确认需要打印吗?")
            XPopup.Builder(ActivityUtils.getTopActivity())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .autoOpenSoftInput(false)
                .asCustom(mConfirmPopup)
                .show()
        }else{
            InitializeUtils.getDefaultMaker()?.show("正在链接打印机")
            InitializeUtils.LinkPrinterModel(ActivityUtils.getTopActivity())
        }
    }

    /**
     * 去皮
     */
    fun peel(){
        InitializeUtils.getDefaultMaker()?.show("正在去皮请稍后")
        /**
         * 去皮
         */
        peel.set(true)
        /**
         * 置零命令
         */
        OpenSerialPort.ZeroOrder()
    }

    /**
     * 计算
     */
    fun calculation(){
        when(mPosition.value){
            0->{
                //稻谷杂质
                mRiceImpurityFragment.calculation()
            }
            1->{
                //稻谷谷外糙米
                mRiceBrownFragment.calculation()
            }
            2->{
                //稻谷出糙率
                mRiceRougheningFragment.calculation()
            }
            3->{
                //稻谷整精米
                mRiceFinishingFragmeent.calculation()
            }
            4->{
                //稻谷黄粒米
                mRiceYellowGrainFragment.calculation()
            }
            5->{
                //互混
                mRiceIntermixingFragment.calculation()
            }
            6->{
                //出米率
                mRiceYieldFragment.calculation()
            }
        }
        /**
         *  编号
         */
        if(TextUtils.isEmpty(mNumber.get())){
            var number = NumberDao.getInstance().acquireNumber()
            if(null != number){
                if(SPUtils.getInstance().getLong("NumberedDate") > 0){
                    val DAY = TimeUtils.getTimeSpan(
                        SPUtils.getInstance().getLong("NumberedDate"),
                        TimeUtils.getNowMills(),
                        TimeConstants.DAY
                    )
                    if (DAY == 0L) {
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordRice.uniqueId = numberString
                        mNumber.set(numberString)
                    }else{
                        SPUtils.getInstance().put("number", 1)
                        SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordRice.uniqueId = numberString
                        mNumber.set(numberString)
                    }
                }
            }
        }
        /**
         * 日期
         */
        var getNowMills = TimeUtils.getNowMills()
        mInspectionDate.set(TimeUtils.millis2String(getNowMills))
        mRecordRice.inspectionDate = getNowMills
    }
    /**
     * 主菜单
     */
    fun mainMenu(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    ActivityUtils.finishActivity(RiceActivity::class.java)
                }
            }
        },"返回主菜单会导致当前数据丢失")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show();
    }
}